package com.xjtu.weixin.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.xjtu.weixin.builder.TextBuilder;
import com.xjtu.weixin.mapper.MpSubscribeMapper;
import com.xjtu.weixin.mapper.MpTextTemplateMapper;
import com.xjtu.weixin.model.entity.MpSubscribe;
import com.xjtu.weixin.model.entity.MpTextTemplate;
import com.xjtu.weixin.service.MpSubscribeService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户关注
 *
 * @author 杨凯
 * @create 2018-09-03 16:54
 **/
@Slf4j
@Service
public class MpSubscribeServiceImpl implements MpSubscribeService {

	@Autowired
	private MpSubscribeMapper subscribeMapper;

	@Autowired
	private MpTextTemplateMapper templateMapper;

	@Override
	public void addMpSubscribe(MpSubscribe subscribe) {
		subscribeMapper.insert(subscribe);
	}

	@Override
	public WxMpXmlOutMessage getResponseMsg(WxMpXmlMessage wxMessage, WxMpService service) {
		EntityWrapper entity = new EntityWrapper<MpSubscribe>();
		entity.orderBy("create_time").last("limit 1");
		List<MpSubscribe> list = subscribeMapper.selectList(entity);
		if(!list.isEmpty()){
			final MpSubscribe subscribe = list.get(0);

			switch (subscribe.getMsgType()){
				case "text":
					final MpTextTemplate textTemplate = templateMapper.selectById(subscribe.getTemplateId());
					return new TextBuilder().build(textTemplate.getTemplateContent(),wxMessage,service);
					default:
						break;
			}
		}
		return new TextBuilder().build("谢谢关注!",wxMessage,service);
	}
}
